// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const TcbRouter = require("tcb-router")
const db = cloud.database()
const blogCollection = db.collection("blog")
const commentCollection = db.collection("blog-comment")
const MAX_LIMIT = 100
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })

  app.router("list", async (ctx, next) => {
      let blogList = await blogCollection.skip(event.start).limit(event.count)
        .where({
          content: { //模糊查询
            $regex: '.*' + event.content,
            $options: 'i'
          }
        })
        .orderBy("createTime", "desc")
        .get()
        .then((res) => {
          return res.data
        })
      ctx.body = blogList
    }),

    app.router("detail", async (ctx, next) => {
      let blogId = event.blogId
      let detail = await blogCollection.where({
          _id: blogId
        })
        .get()
        .then((res) => {
          return res.data
        })
      //评论查询
      const countResult = await blogCollection.count()
      const total = countResult.total
      let commentList = {
        data: []
      }
      if (total > 0) {
        const batchTimes = Math.ceil(total / MAX_LIMIT)
        const tasks = []
        for (let i = 0; i < batchTimes; i++) {
          let promise = commentCollection.skip(i * MAX_LIMIT)
            .limit(MAX_LIMIT)
            .where({
              blogId
            })
            .orderBy("createTime", "desc")
            .get().then((res) => {
              return res.data
            })
          tasks.push(promise)
        }
        if (tasks.length > 0) {
          commentList = (await Promise.all(tasks)).reduce((acc, curr) => {
            return {
              data: acc.data.concat(curr.data)
            }
          })
        }
      }
      ctx.body = {
        commentList,
        detail,
      }
    }),

    app.router("deleteComment", async (ctx, next) => {
      let deleteComment = await commentCollection
        .where({
          _id: event.id
        }).remove({
          success: function (res) {
            return res.data
          }
        })
        ctx.body = deleteComment
    })
    app.router("deleteBlog", async (ctx, next) => {
      let deleteBlog = await blogCollection
        .where({
          _id: event.id
        }).remove({
          success: function (res) {
            return res.data
          }
        })
        ctx.body = deleteBlog
    })

  return app.serve()
}